package wiiusej.hardwareControllers;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import wiiusej.Wiimote;

public class PermanentLEDContoller implements Runnable{

	private BlockingQueue<Integer> fromEnergy;
	
	private Wiimote myWiimote;
	
	private int turnedONLights = 0;
	private long blinkFreq = 500; //MILLISECONDS
	
	//Logger
	Logger fileLogger;
	
	public PermanentLEDContoller(Wiimote myWiimote, BlockingQueue<Integer> fromEnergy){
		
		this.fromEnergy = fromEnergy;
		this.myWiimote = myWiimote;
		
		myWiimote.setLeds(false, false, false, false);
		
		PropertyConfigurator.configure("log4j.properties");
		this.fileLogger = Logger.getLogger("ledController");
		
	}
	
	@Override
	public void run() {
		while(true){			
			try {
				Integer command = fromEnergy.take();				
				fileLogger.info("Received Command: " + command);
				
				processCommand(command);
				
				
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	
	private boolean uploadLights(Integer command){		
		if(turnedONLights != command){
			turnedONLights = command;
			return true;
		}else{
			return false;
		}
	}
	
	private void processCommand(Integer command){
		
		if(uploadLights(command)){
			
			switch(turnedONLights){
			
			case 1: 
				myWiimote.setLeds(true, false, false, false);
				break;
				
			case 2:
				myWiimote.setLeds(true, true, false, false);
				break;
				
			case 3:
				myWiimote.setLeds(true, true, true, false);
				break;
			
			case 4:
				myWiimote.setLeds(true, true, true, true);
				break;
			
			case 5:
				fileLogger.info("Calling to blink method()");
				blinkedLEDS();
				break;
			
			}
			
		}
		
		
	}

	private void blinkedLEDS() {

		Integer command;
		fileLogger.info("Blinking Ligths");
		try {			
			do{
				command = fromEnergy.poll();
				
				if(command == null){
					fileLogger.info("TurnOff");
					myWiimote.setLeds(false, false, false, false);
					Thread.sleep(200);
					
					command = fromEnergy.poll();		
					fileLogger.info("Received Command from Blink(): " + command);
					
					if(command == null){
						myWiimote.setLeds(true, true, true, true);
						fileLogger.info("TurnOn");
						Thread.sleep(200);						
					}					
				}				
			}while(command == null);			
			
			fromEnergy.clear();
			fromEnergy.put(command);
			
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		
		
			
		
		
		
		
	}
}
